<style type="text/css">
	.border-container::after {
		content: "Novo Pedido";
	}
</style>
<div class="container">
	{{ Form::open(array('url' => 'order', 'class' => 'form-horizontal', 'role' => 'form')) }}
		<div class="border-container">
			@if (!$errors->isEmpty())
			<div class="alert alert-danger">
				<strong>Ocorreram os seguintes erros:</strong>
				{{ HTML::ul($errors->all()) }}
			</div>
			@endif
			
			<ul class="nav nav-tabs">
				<li class="active"><a href="#identification" data-toggle="tab">Identificação</a></li>
	            <li><a href="#components" data-toggle="tab">Componentes</a></li>
			</ul>
			
			<div class="tab-content">
            	<div class="tab-pane active" id="identification">
					<div class="form-group">
						<label for="order_number" class="col-sm-2 control-label">Nro Pedido</label>
						<div class="col-sm-4">
		                	{{ Form::text('order_number', null, array('class'=>'form-control', 'maxlength' => 15, 'id' => 'orderNumber', 'autocomplete' => 'off')) }}
		                	<span class="loading small" style="display:none">Carregando...</span>
						</div>
            		</div>
            		
            		<div class="form-group">
						<label for="customer_id" class="col-sm-2 control-label">Cliente</label>
						<div class="col-sm-9">
		                	{{ Form::select('customer_id', $customers, "", array('class'=>'form-control', 'id' => 'customerId')) }}
						</div>
            		</div>
            		
            		<div class="form-group">
						<label for="production_number" class="col-sm-2 control-label">Ordem de Produção</label>
						<div class="col-sm-4">
		                	{{ Form::text('production_number', null, array('class'=>'form-control', 'maxlength' => 9, 'id' => 'productionNumber', 'autocomplete' => 'off')) }}
						</div>
            		</div>
            		
            		<div class="form-group">
						<label for="amount" class="col-sm-2 control-label">Qtd a Produzir</label>
						<div class="col-sm-4">
		                	{{ Form::text('amount', null, array('class'=>'form-control', 'maxlength' => 9, 'id' => 'amount', 'autocomplete' => 'off')) }}
						</div>
            		</div>
            		
            		<div class="form-group">
						<label for="order_date" class="col-sm-2 control-label">Data de Entrada</label>
						<div class="col-sm-4">
							<div class="input-group date">
			                	{{ Form::text('order_date', null, array('class'=>'form-control', 'id' => 'orderDate', 'autocomplete' => 'off')) }}
			                	<span class="input-group-addon"><i class="glyphicon glyphicon glyphicon-calendar"></i></span>
			                </div>
						</div>
            		</div>
            		
            		<div class="form-group">
						<label for="production_end_date" class="col-sm-2 control-label">Data de Entrega</label>
						<div class="col-sm-4">
							<div class="input-group date">
			                	{{ Form::text('production_end_date', null, array('class'=>'form-control', 'id' => 'productionEndDate', 'autocomplete' => 'off')) }}
			                	<span class="input-group-addon"><i class="glyphicon glyphicon glyphicon-calendar"></i></span>
			                </div>
						</div>
            		</div>
            		
            		<div class="form-group">
						<label for="production_start_date" class="col-sm-2 control-label">Início da Produção</label>
						<div class="col-sm-4">
							<div class="input-group date">
			                	{{ Form::text('production_start_date', null, array('class'=>'form-control', 'id' => 'productionStartDate', 'autocomplete' => 'off')) }}
			                	<span class="input-group-addon"><i class="glyphicon glyphicon glyphicon-calendar"></i></span>
			                </div>
						</div>
            		</div>
            	</div>
            	
            	<div class="tab-pane" id="components">
            	
		            <div id="componentsHeader" class="form-group" style="display: none;">
		            	<div class="col-sm-2 centered">
		            		<label>Tipo</label>
		            	</div>
		            	<div class="col-sm-2 centered">
		            		<label>Código do CIGAM</label>
		            	</div>
		            	<div class="col-sm-1 centered">
		            		<label>Qtd</label>
		            	</div>
		            	<div class="col-sm-4">
		            		<label>Nome do Componente</label>
		            	</div>
		            	<div class="col-sm-3">
		            		<label>Ações</label>
		            	</div>
		            </div>
            	
            		@if (empty($oldComponents))
	            		<div id="baseProductGroup" class="form-group">
	            			<label for="baseProduct" class="col-sm-2 control-label">Partir de: </label>
							<div class="col-sm-9">
								<input type="hidden" id="baseProduct" class="form-control" />
							</div>
							<div class="col-sm-1">
								<button id="loadProduct" class="btn btn-primary">OK</button>
							</div>
						</div>
					@else
						@foreach ($oldComponents as $key => $component)
							<div class="form-group component-group">
								<div class="col-sm-2" style="padding-right: 3px;">
									<select name="accessories[]" class="form-control cboOperationType">
										<option value="0"@if ($oldAccessories[$key] == 0) selected@endif>Operação</option>
										<option value="1"@if ($oldAccessories[$key] == 1) selected@endif>Insumo</option>
									</select>
								</div>
								<div class="col-sm-2 col-component">
									<input type="text" class="form-control txtCigamCode" name="cigamCodes[]" value="{{ $oldCigamCodes[$key] }}" autocomplete="off" required="required"@if ($oldAccessories[$key] == 1) readonly="readonly"@endif>
								</div>
								<div class="col-sm-1 col-component">
					    			<input type="text" class="form-control" name="amounts[]" value="{{ $oldAmounts[$key] }}" autocomplete="off" required="required">
					  			</div>
								<div class="col-sm-4 col-component">
									<input type="text" class="form-control ui-autocomplete-input" name="components[]" value="{{ $component }}" autocomplete="off" required="required">
								</div>
								<div class="col-sm-3 col-component">
									<input type="hidden" name="costCentres[]" value="{{ $oldCostCentres[$key] }}">
									<button type="button" class="btn btn-danger btn-sm btnRemoveComponent" data-toggle="tooltip" data-placement="top" title="Remover Componente">
										<span class="glyphicon glyphicon-trash"></span>
									</button>
								</div>
							</div>
						@endforeach
					@endif
            		<div id="addComponentGroup" class="form-group" @if (empty($oldComponents)) style="display: none" @endif>
						<div class="col-sm-9">
							<button id="btnAddComponent" type="button" class="btn btn-primary">Adicionar componente</button>
						</div>
					</div>
            	</div>
            </div>
      	</div>
      
      	{{ Form::submit('Cadastrar Pedido', array('id' => 'btn-save-order', 'class'=>'btn btn-primary', 'data-loading-text' => 'Aguarde...'))}}
		{{ HTML::link('order', 'Cancelar', array('class' => 'btn btn-default', 'style'=>'float: right')) }}
	{{ Form::close() }}
</div>
<script type="text/javascript">
	var allCostsCentres = {{ $costsCentres }};
	$(document).ready(function() {
		var startingProducts = {{ $products }};
		startingProducts.unshift(startingProducts, {"id": "", "name": "Novo produto"});

/*		$("input[name='components[]']").autocomplete({
			source: function( request, response ) {
				$.ajax({
					url: $.rootUrl + "product/componentsSuggestions",
					data: {term: request.term},
					dataType: "json",
					success: function( data ) {
						response( $.map( data, function( item ) {
							return {
								label: item.code + ' - ' + item.name,
								name: item.name,
								value: item.costs_centres,
								code: item.code,
								isAccessory: item.accessory
							}
						}));
					}
				});
			},
			select: function( event, ui ) {
				var targetComponent = $(this).closest('.form-group');
				this.value = ui.item.name;
				$("select[name='accessories[]']", targetComponent).val(ui.item.isAccessory + "");
				$("input[name='cigamCodes[]']", targetComponent).val(ui.item.code);
				$("input[name='costCentres[]']", targetComponent).val($(ui.item.value).map(function() { return this.id; }).get().join());
				event.preventDefault();
			},
			focus: function (event, ui) {
				this.value = ui.item.name;
				event.preventDefault();
			},
			minLength: 3,
			delay: 200
		});*/

		$('#customerId').select2({
			allowClear: true,
			placeholder: 'Selecione o cliente'
		});
		
		$("#baseProduct").select2({
			data:{ results: startingProducts, text: function(item) { return item.name; } },
			formatSelection: function(item) { return item.name; },
			formatResult: function(item) { return item.name; }
		});

		$("input[name='costCentres[]']").costsCentres({ costsCentres: allCostsCentres });

		$("#loadProduct").click(function(e) {
			var productId = $("#baseProduct").val();
			if (productId != "") {
				$.post(
					$.rootUrl + 'product/retrieveComponents',
					{ id: productId },
					function(productComponents) {
						var componentSourceCode = $('#tplNewComponentWithCostCentre').html();
						for (var i = 0; i < productComponents.length; i++) {
							var tpl = Handlebars.compile(componentSourceCode) 
								newComponent = $(tpl(
													{ isAccessory: productComponents[i].accessory == 1,
													  code: productComponents[i].code,
													  name: productComponents[i].name,
													  amount: productComponents[i].amount,
													  costsCentres: $(productComponents[i].costs_centres).map(function() { return this.id; }).get().join()
													}
												)
								);
						
							$("#addComponentGroup").before(newComponent);
							$("input[name='costCentres[]']", newComponent).costsCentres({ costsCentres: allCostsCentres });
/*							$("input[name='components[]']").autocomplete({
								source: function( request, response ) {
									$.ajax({
										url: $.rootUrl + "product/componentsSuggestions",
										data: {term: request.term},
										dataType: "json",
										success: function( data ) {
											response( $.map( data, function( item ) {
												return {
													label: item.code + ' - ' + item.name,
													name: item.name,
													value: item.costs_centres,
													code: item.code,
													isAccessory: item.accessory
												}
											}));
										}
									});
								},
								select: function( event, ui ) {
									var targetComponent = $(this).closest('.form-group');
									this.value = ui.item.name;
									$("select[name='accessories[]']", targetComponent).val(ui.item.isAccessory + "");
									$("input[name='cigamCodes[]']", targetComponent).val(ui.item.code);
									$("input[name='costCentres[]']", targetComponent).val($(ui.item.value).map(function() { return this.id; }).get().join());
									event.preventDefault();
								},
								focus: function (event, ui) {
									this.value = ui.item.name;
									event.preventDefault();
								},
								minLength: 3,
								delay: 200
							});*/
						}

						$("#addComponentGroup").show();
						$("#baseProductGroup").hide();
					}
				);
			} else {
				$("#btnAddComponent").trigger("click");
				$("#addComponentGroup").show();
				$("#baseProductGroup").hide();
			}

			$("#componentsHeader").show();
			
			e.preventDefault();
		});

		$('#orderNumber').blur(function() {
			if ($(this).val() !== '') {
				$('.form-control').attr('disabled', 'disabled');
				$('.loading').show();
				$.get($.rootUrl + 'order/getByOrderNumber/' + $(this).val(), function(data) {
					var $client = $('#customerId'),
						$orderDate = $('#orderDate'),
						$productionNumber = $('#productionNumber'),
						loaded = false;
					
					if (data.length > 0) {
						var order = data[0];

						loaded = true;

						$client.select2('val', order.customer_id);
						$orderDate.datepicker('setDate', order.order_date.split('-').reverse().join('/'));
						$productionNumber.val(order.production_number + 1);
					} else {
						$client.select2('val', '');
						$orderDate.val('');
						$productionNumber.val('');
					}

					$('.form-control').removeAttr('disabled');
					$('.loading').hide();

					if (loaded) {
						$productionNumber.focus();
					} else {
						$client.select2('focus');
					}
				});
			}
		});

		$('#orderDate').datepicker('option', 'onClose', function() {
			var $orderDate = $('#orderDate'),
				orderDateArray = $orderDate.val().split('/'),
				$productionStart = $('#productionStartDate');
				
				if ($orderDate.val() !== '' && $orderDate.val() !== '__/__/____' && $productionStart.val() === '') {
					var orderDate = $orderDate.datepicker('getDate'),
						currentDate = new Date();
		
					currentDate.setHours(0);
					currentDate.setMinutes(0);
					currentDate.setSeconds(0);
					currentDate.setMilliseconds(0);
		
					if (orderDate.getTime() < currentDate.getTime()) {
						$productionStart.datepicker('setDate', currentDate);
					} else {
						$productionStart.datepicker('setDate', orderDate);
					}
				}
			}
		);
	});
</script>